import {ElMessage} from "element-plus";
import {createRouter, createWebHistory} from 'vue-router'
import { useUserStore } from "../stores/user";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'layout',
      children: [
        {
          path: '',
          name: 'home',
          component: () => import('../views/home/Home.vue'),
        },
        {
          path: ':type',
          name: 'category',
          component: () => import('../views/category/Category.vue'),
        },
        {
          path: 'top',
          name: 'top',
          component: () => import('../views/top/Top.vue'),
        },
        {
          path: 'user/bookcase',
          name: 'user/bookcase',
          meta: {
            tip:'永不丢失的书架 , 与电脑同步',
            isAuth:true
          },
          component: () => import('../views/bookcase/BookCase.vue'),
        },
        {
          path: 'login',
          name: 'login',
          component: () => import('../views/user/Login.vue'),
        },
        {
          path: 'register',
          name: 'register',
          component: () => import('../views/user/Register.vue'),
        },
        {
          path: 'bookcase',
          name: 'bookcase',
          meta: {
            tip:'浏览记录（只限同一游览器）'
          },
          component: () => import('../views/bookcase/BookCase.vue'),
        },
       {
        path: 'book/:id',
        name: 'book',
        component: () => import('../views/book/Book.vue'),
      },
      {
        path: 'book/:bookId/:chapterId',
        name: 'chapter',
        component: () => import('../views/chapter/Chapter.vue'),
      },
      {
        path: 'search',
        name: 'search',
        component: () => import('../views/search/Search.vue'),
      },
      ]
    },
  ],
  scrollBehavior() {
    return {
      top: 0
    }
  }
})


// 配置路由导航
router.beforeEach((to, from, next) => {
    // 判断资源是否要拦截
    if (to.matched.some(route => route.meta.isAuth)) {
      // 如果资源要拦截, 判断是否有token
      const token = useUserStore().token
      // 如果token存在, 直接放行
      if (token) {
        next()
      } else {
        // 没有token 跳转登录页
        alert("请先登录")
        next({
          path: "/login"
        })
      }
    } else {
      // 请求的资源不需要拦截 直接放行
      next()
    }
  }
)


export default router
